package com.study.jdbc.dao.impl;

import java.io.Serializable;
import java.util.List;

import com.study.jdbc.dao.CustomerDao;
import com.study.jdbc.domain.Customer;
import com.study.jdbc.frame.BeanHandle;
import com.study.jdbc.frame.BeanListHandle;
import com.study.jdbc.frame.JDBCAssist;
import com.study.jdbc.utils.DBCPUtil;

/**
* @Name: CustomerDaoJDBCImpl
* @Description: 用户CRUD操作dao接口JDBC实现类：使用自定义JDBC工具类（使用数据源）
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-16 下午7:43:46 
* @Version: V1.0
 */
public class CustomerDaoJDBCImpl2 implements CustomerDao {
	
	private JDBCAssist jdbcAssist = new JDBCAssist(DBCPUtil.getDataSource()) ;

	@Override
	public Customer findCustomerById(Serializable id) {
		String sql = "select id, name, gender, birthday, cellphone, email, preference, type, description " +
				"from t_customer " +
				"where id = ? ; " ;
		Customer customer = (Customer) jdbcAssist.query(sql, new BeanHandle(Customer.class), id) ;
		return customer ;
	}

	@Override
	public List<Customer> findAllCustomers() {
		String sql = "select id, name, gender, birthday, cellphone, email, preference, type, description from t_customer ; " ;
		List<Customer> list = (List<Customer>) jdbcAssist.query(sql, new BeanListHandle(Customer.class)) ;
		return list ;
	}

	@Override
	public void saveCustomer(Customer customer) {
		String sql = "insert into " +
				" t_customer(id, name, gender, birthday, cellphone, email, preference, type, description) " +
				" values(?, ?, ?, ?, ?, ?, ?, ?, ?) ; " ;
		jdbcAssist.update(sql, 
				customer.getId(),
				customer.getName(),
				customer.getGender(),
				customer.getBirthday(),
				customer.getCellphone(),
				customer.getEmail(),
				customer.getPreference(),
				customer.getType(),
				customer.getDescription()) ;
	}

	@Override
	public void updateCustomer(Customer customer) {
		String sql = "update t_customer set " +
				" name = ?, " +
				" gender = ?, " +
				" birthday = ?, " +
				" cellphone = ?, " +
				" email = ?, " +
				" preference = ?, " +
				" type = ?, " +
				" description = ? " +
				" where id = ? ; " ;
		jdbcAssist.update(sql, 
				customer.getName(),
				customer.getGender(),
				customer.getBirthday(),
				customer.getCellphone(),
				customer.getEmail(),
				customer.getPreference(),
				customer.getType(),
				customer.getDescription(),
				customer.getId()) ;
	}

	@Override
	public void deleteCustomerById(Serializable id) {
		String sql = "delete from t_customer where id = ? ; " ;
		jdbcAssist.update(sql, id) ;
	}

	@Override
	public int getTotalRecordsCount() {
		return findAllCustomers().size() ;
	}

	@Override
	public List<Customer> findPageRecords(int startIndex, int pageSize) {
		String sql = "select id, name, gender, birthday, cellphone, email, preference, type, description" +
				" from t_customer" +
				" limit ?, ? ; " ;
		List<Customer> list = (List<Customer>) jdbcAssist.query(sql, new BeanListHandle(Customer.class), startIndex, pageSize) ;
		return list ;
	}
}


